package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.callback.SendEmailCallback;
import com.cskaoyan.order.biz.callback.TransCallback;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.constant.OrderItemConstant;
import com.cskaoyan.order.converter.OrderConverter;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dto.CartProductDto;
import com.cskaoyan.order.utils.GlobalIdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * 初始化订单 生成订单
 */

@Slf4j
@Component
public class InitOrderHandler extends AbstractTransHandler {

    @Autowired
    OrderConverter orderConverter;

    @Autowired
    SendEmailCallback sendEmailCallback;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    GlobalIdGeneratorUtil globalIdGeneratorUtil;


    private final String ORDER_GLOBAL_ID_CACHE_KEY = "ORDER_ID";
    private final String ORDER_ITEM_GLOBAL_ID_CACHE_KEY = "ORDER_ITEM_ID";

    @Override
    public TransCallback getTransCallback() {
        return sendEmailCallback;
    }

    @Override
    public boolean isAsync() {
        return false;
    }

    /**
     * 初始化订单，向数据库的订单表和订单商品关联表插入数据，订单状态为初始化状态
     *
     * @param context 包含请求参数的对象
     * @return boolean
     * @author Chen_Feng
     * @since 2022/07/09 13:21
     */
    // @Transactional
    @Override
    public boolean handle(TransHandlerContext context) {

        Date date = new Date();
        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        createOrderContext.setCreateTime(date);
        createOrderContext.setUpdateTime(date);

        // 利用发号器获得一个随机orderId,并赋值给context
        String orderId = globalIdGeneratorUtil.getNextSeq(ORDER_GLOBAL_ID_CACHE_KEY, 1);
        createOrderContext.setOrderId(orderId);

        // 封装订单Do对象
        Order order = context2Order(createOrderContext);

        // 向订单表中插入一条数据
        try {
            orderMapper.insertSelective(order);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(), OrderRetCode.INIT_ORDER_EXCEPTION.getMessage());
        }

        // 获得订单包含的商品信息List,向订单商品表中插入数据
        doInsertOrderItem(createOrderContext, orderId);

        // 为context增添nickname
        createOrderContext.setBuyerNickName(createOrderContext.getUserName());

        return true;
    }

    /**
     * 根据Context对象转化出一个Order对象
     *
     * @param createOrderContext
     * @return com.cskaoyan.order.dal.entitys.Order
     * @author Chen_Feng
     * @since 2022/07/10 23:48
     */
    private Order context2Order(CreateOrderContext createOrderContext) {
        Order order = new Order();
        order.setOrderId(createOrderContext.getOrderId());
        order.setPayment(createOrderContext.getOrderTotal());
        order.setStatus(OrderConstants.ORDER_STATUS_INIT);
        order.setCreateTime(createOrderContext.getCreateTime());
        order.setUpdateTime(createOrderContext.getUpdateTime());
        order.setUserId(createOrderContext.getUserId());
        order.setBuyerNick(createOrderContext.getUserName());

        return order;
    }

    /**
     * 向订单商品表中插入数据
     *
     * @param createOrderContext
     * @param orderId
     * @return void
     * @author Chen_Feng
     * @since 2022/07/10 23:57
     */
    private void doInsertOrderItem(CreateOrderContext createOrderContext, String orderId) {
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        for (CartProductDto cartProductDto : cartProductDtoList) {
            OrderItem orderItem = orderConverter.cartProductDto2OderItem(cartProductDto);

            // 通过发号器获得id
            String orderItemId = globalIdGeneratorUtil.getNextSeq(ORDER_ITEM_GLOBAL_ID_CACHE_KEY, 1);

            // 补充缺失的orderItem数据
            Timestamp timestamp = new Timestamp(createOrderContext.getCreateTime().getTime());
            BigDecimal totalFee = cartProductDto.getSalePrice().multiply(new BigDecimal(cartProductDto.getProductNum()));
            orderItem.setId(orderItemId);
            orderItem.setOrderId(orderId);
            orderItem.setTotalFee(totalFee.doubleValue());
            orderItem.setStatus(OrderItemConstant.LOCK_STOCK_STATUS);
            orderItem.setCreate(timestamp);
            orderItem.setUpdate(timestamp);

            // 向订单商品关联表中插入一条数据
            try {
                orderItemMapper.insertSelective(orderItem);
            } catch (Exception e) {
                e.printStackTrace();
                throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(), OrderRetCode.INIT_ORDER_EXCEPTION.getMessage());
            }
        }
    }
}
